/*
 * @Author: yangzonglong
 * @Date: 2020-07-02 09:08:58
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2020-12-10 15:52:26
 * @Auditor: 
 */
import server from './../../utils/server/server';
import i18n from './../../app/i18n';
import { ApiModelProps } from './interface';

const TYPE = 'modalTableInModel';

export async function getModelApi(module: string, model: string, pageModelCode?: string) {
  try {
    const url = `/bk/api/${module}/${model}/getModel`;
    const { apiModels = [], pageModels = [], attributes: _attributes } = await server(url, {});
    const curApiModel: ApiModelProps = apiModels.find((item: ApiModelProps) => item.type === TYPE);
    const language = i18n.language === 'zh-CN' ? 'cn' : i18n.language;
    
    const columns: any[] = [];
    const searchFields: string[] = [];
    const searchFieldsText: string[] = [];

    let attributes = pageModels.length ? pageModels[0].fields : _attributes;
    
    if(pageModelCode) {
      const curPageModel = pageModels.find((item: any) => item.pageModelCode === pageModelCode);
      attributes = curPageModel?.fields || [];
    }
    
    attributes.forEach((item: any, index: number) => {
      const field = item.fieldName;
      const title = item.locales?.[language];

      if(curApiModel.columns.includes(field)) {
        if(item.filter) {
          searchFields.push(field);
          searchFieldsText.push(title);
        }

        columns.push({
          ...item,
          dataIndex: field,
          sorter: item.sort,
          title
        })
      }
    })

    const locales = curApiModel.locales;

    return { 
      columns, 
      searchFields, 
      searchFieldsText,
      title: locales[i18n.language === 'zh-CN' ? 'cn' : 'en'] as string,
      url: `/bk/api/${module}/${model}/find`,
      fieldNames: curApiModel.fieldNames,
      query: {}
    }

  } catch (error) {
    return { 
      columns: [], 
      searchFields: [], 
      searchFieldsText: [],
      fieldNames: {
        value: '',
        label: ''
      },
      title: '',
      url: '',
      query: {}
    }
  }
}